package cc.customer.SocketIo;

import cc.customer.SocketIo.projo.PushEvent;
import cc.customer.SocketIo.projo.PushMessage;
import cc.customer.common.utils.DateUtil;
import cc.customer.rabbit.dao.CconvRecordMapper;
import cc.customer.rabbit.domain.CconvRecord;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: customer
 * Created by yhsh on 2019/10/30 8:59
 * version 2.0
 * 方法说明
 */
public class SocketIOService {

	private static final Logger logger = LoggerFactory.getLogger(SocketIOService.class);
	// 用来存已连接的客户端
	//private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

	/**按照连接 session 处理客户端**/
	//private static List<UUID> listClient = new ArrayList<UUID>();

	/*@Autowired
	private SocketIOServer socketIOServer;*/

	/*@Autowired
	private CconvRecordMapper cconvRecordMapper;*/


	/**
	 * Spring IoC容器创建之后，在加载SocketIOServiceImpl Bean之后启动
	 *
	 * @throws Exception
	 */
	/*@PostConstruct*/
	/*private void autoStartup()  {
		try{
			start();
		}catch (Exception e){
			logger.error("初始化socket 连接失败："+e.getMessage());
		}
	}*/
	/**
	 * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
	 *
	 * @throws Exception
	 */
	/*@PreDestroy
	private void autoStop() {
		stop();
	}
	public void start() throws Exception {
		// 监听客户端连接
		socketIOServer.addConnectListener(client -> {
			String loginUserNum = getParamsByClient(client);
			if (loginUserNum != null) {
				logger.info(loginUserNum+": 连接成功  RemoteAddress:  " + client.getRemoteAddress());
				clientMap.put(loginUserNum, client);
			}
		});
		// 监听客户端断开连接
		socketIOServer.addDisconnectListener(client -> {
			String loginUserNum = getParamsByClient(client);
			if (loginUserNum != null) {
				clientMap.remove(loginUserNum);
				System.out.println("断开连接： " + loginUserNum);
				client.disconnect();
			}
		});
		// 处理自定义的事件，与连接监听类似
		socketIOServer.addEventListener("text", Object.class, (client, data, ackSender) -> {
			// TODO do something
			client.getHandshakeData();
			System.out.println( " 客户端：************ " + data);
			JSONObject jb = JSONObject.parseObject((String) data);
			*//*CconvRecord cconvRecord = new CconvRecord();
			cconvRecord.setcCordUser(jb.getString("username"));cconvRecord.setcCordTitle(jb.getString("info"));
			cconvRecord.setcCordType(jb.getString("type"));cconvRecord.setcCordSession(jb.getString("uuid"));
			cconvRecord.setcCordTime(DateUtil.getCurrentDate(DateUtil.FULL_DATE_FORMAT));
			cconvRecordMapper.insert(cconvRecord);*//*
		});
		socketIOServer.start();
	}
	public void stop() {
		if (socketIOServer != null) {
			socketIOServer.stop();
			socketIOServer = null;
		}
	}
	*//**推送个人事件**//*
	public void pushMessageToUser(PushMessage pushMessage) {
		String loginUserNum = pushMessage.getUserid();
		if (StringUtils.isNotBlank(loginUserNum)) {
			SocketIOClient client = clientMap.get(loginUserNum);
			if (client != null)
				client.sendEvent(PushEvent.PUSH_PERSON_MESSAGE, pushMessage);
		}
	}
	*//**推送月报事件**//*
	public void pushMessageToMonth(PushMessage pushMessage){
		List<String> listUser = pushMessage.getDeptUsers();
		if (!listUser.isEmpty()){
			for (String userid:listUser){
				SocketIOClient client = clientMap.get(userid);
				if (client != null)
					client.sendEvent(PushEvent.PUSH_MONTH_REPORT, pushMessage);
			}
		}
	}
	*//**推动部门事件**//*
	public void pushMessageToDept(PushMessage pushMessage){
		List<String> listUser = pushMessage.getDeptUsers();
		if (!listUser.isEmpty()){
			for (String userid:listUser){
				SocketIOClient client = clientMap.get(userid);
				if (client != null)
					client.sendEvent(PushEvent.PUSH_DEPT_RECEVICE, pushMessage);
			}
		}
	}
	*//**推动其他事件**//*
	public void pushMessageToOther(PushMessage pushMessage){
		List<String> listUser = pushMessage.getDeptUsers();
		if (!listUser.isEmpty()){
			for (String userid:listUser){
				SocketIOClient client = clientMap.get(userid);
				if (client != null)
					client.sendEvent(PushEvent.PUSH_Other_RECEVICE, pushMessage);
			}
		}
	}
	*//**
	 * 此方法为获取client连接中的参数，可根据需求更改
	 * @param client
	 * @return
	 *//*
	private String getParamsByClient(SocketIOClient client) {
		// 从请求的连接中拿出参数（这里的loginUserNum必须是唯一标识）
		Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
		List<String> list = params.get("loginUserNum");
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public static Map<String, SocketIOClient> getClientMap() {
		return clientMap;
	}

	public static void setClientMap(Map<String, SocketIOClient> clientMap) {
		SocketIOService.clientMap = clientMap;
	}*/
}
